package com.changgou.thymeleaf.controller;

import com.changgou.thymeleaf.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import java.io.File;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Controller
@RequestMapping("/demo")
public class DemoController {

    @GetMapping("/test")
    public String test(Model model,String id){
        //前台的表单提交参数
        System.out.println(id);

        //list集合
        User user1 = new User(1,"一号","北京");
        User user2 = new User(2,"二号","上海");
        User user3 = new User(3,"三号","南京");
        ArrayList<User> users = new ArrayList<>();
        users.add(user1);
        users.add(user2);
        users.add(user3);

        //map
        HashMap<String, Object> map = new HashMap<>();
        map.put("map1","哈哈");
        map.put("map2","呵呵");

        //数组
        String[] names = {"张三","李四","王五"};

        model.addAttribute("user1",user1);
        model.addAttribute("hello","hello world");
        model.addAttribute("users",users);
        model.addAttribute("map",map);
        model.addAttribute("names",names);
        model.addAttribute("id",id);
        //Date日期
        model.addAttribute("now",new Date());
        model.addAttribute("age",20);
        return "demo";
    }

    @Autowired
    private TemplateEngine templateEngine;

    @GetMapping("/test2")
    @ResponseBody
    public void test2(Model model){
        Context context = new Context();
        Map<String, Object> dataMap = new HashMap<>();
//        dataMap.put("a", "1");
//        dataMap.put("b", "2");
//        dataMap.put("c", "3");
//        context.setVariables(dataMap);
        context.setVariable("a","11");
        context.setVariable("b","22");
        context.setVariable("c","33");

        File file = new File("F:\\static");
        if(!file.exists()){
            file.mkdirs();
        }
        /**
         * 1.模板路径
         * 2.context对象(参数)
         * 3.字符输出流
         */
        PrintWriter printWriter = null;
        try {
            File file1 = new File(file + "\\a.html");
            printWriter = new PrintWriter(file1);
            templateEngine.process("c",context,printWriter);
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            try {
                printWriter.close();
            }catch (Exception e){
                e.printStackTrace();
            }
        }
//        model.addAttribute("a","11");
//        model.addAttribute("b","22");
//        model.addAttribute("c","33");
    }
}
